<?php
/**
 * Created by PhpStorm.
 * User: cy
 * Date: 18-4-26
 * Time: 上午4:30
 * 使用memcache作为锁驱动
 */

class MemcacheLock implements Lock
{
    private $memcache;//memcache对象
    public function __construct($options)
    {

        $this->memcache = new Memcache();
    }

    /**
     * 尝试对数据进行加锁
     * @param $key
     * @param int $timeout
     * @throws Exception
     */
    public function getLock($key, $timeout=self::EXPIRE)
    {
        //是否已存在锁
        $res=$this->memcache->getCache($key);
        if($res) throw new Exception('当前数据已被锁定，不可操作');

        //加锁
        if(!$this->memcache->setCache($key,1,$timeout)){
            throw new Exception('加锁失败');
        }
    }

    /**
     * 释放锁
     * @param $key
     */
    public function releaseLock($key)
    {
        $this->memcache->delete($key);
    }
}